package edu.hunau.cxb19.oop.class23;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
//使用java的静态导入：导入Collectors中的所有的静态方法
import static java.util.stream.Collectors.*;

import java.util.Arrays;

import org.junit.Test;

/**
 *
 * @author hb
 *
 *         2020-03-26 15:07:02
 */
public class StreamTest {

	@Test
	public void createStream() {
		Integer[] arr = { 123, 123, 34, 5, 456 };
		Stream<Integer> stream01 = Stream.of(arr);

	}

	@Test
	public void filterTest() {
		Stream<Apple> stream = Apple.getDatas().stream();
		// 获得所有的红苹果
		Stream<Apple> filterStream = stream.filter((a) -> {
			System.out.println("filter方法执行");
			return a.getColor().equals("red");
		});
		System.out.println(filterStream);
		// 输出苹果的内容
		filterStream.forEach(System.out::println);

	}

	@Test
	public void filterTest02() {
		Apple.getDatas().parallelStream().filter((a) -> a.getColor().equals("red")).forEach(System.out::println);

	}

	@Test
	public void countTest() {
		long count = Apple.getDatas()
				       .stream()
				       .filter(a -> a.getColor().equals("red"))
				       .count();
	    System.out.println(count);
	}
	
	@Test
	public void collectTest() {
	     List<Apple> redApples = Apple.getDatas()
				       .stream()
				       .filter(a -> a.getColor().equals("red"))
				       .collect(toList());
	    System.out.println(redApples);
	    
	}
	
	@Test
	public void distinctTest() {
		int[] arr= {1,1,2,3,3,10,3,8,9,4,4,5,6,6,6,6,7};
		//要获得忽略前两个的偶数
		Arrays
		.stream(arr)
		.filter(i->i%2==0)  //获得偶数
		.distinct()   //去重复
		.skip(2)
		.forEach(System.out::println);
	}
	
	@Test
	public void mapTest() {
		List<Integer> collect = Apple.getDatas()
							    .stream()
							    .filter(a->a.getColor().equals("red"))
							    .map(Apple::getWeight)
							    .collect(toList());
		System.out.println(collect);
	}
	
	@Test
	public void flatMapTest() {
		String[] datas= {"Hello","World"};
		//获得组成单词的字符列表{"H","e","l","W","r","d"}
		String[] hello = "Hello".split("");
		System.out.println(Arrays.toString(hello));//[H, e, l, l, o]
		String[] world = "World".split("");
		System.out.println(Arrays.toString(world));//[W, o, r, l, d]
		
		List<String[]> r01 = Arrays.stream(datas)
							      .map(str->str.split(""))  //Stream<String[]>
							      .distinct()
							      .collect(toList());
		
		 List<String> r02 = Arrays.stream(datas)
							      .map(str->str.split(""))  //Stream<String[]>
							      .flatMap(Arrays::stream)  //.flatMap(array-> Arrays.stream(array))    Stream<String>
							      .distinct()
							      .collect(toList());
		 System.out.println(r02);
	}
}
 